const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment');
const { default: BigNumber } = require('bignumber.js');

module.exports = class extends Base {
  async vatPanelAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const incomeTotal =
      (await this.model('zengzhi_detail')
        .where({
          status: 1,
          inout_type: 1,
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;
    const outputTotal =
      (await this.model('zengzhi_detail')
        .where({
          status: 1,
          inout_type: 2,
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;

    const unInTotal =
      (await this.model('zengzhi_detail')
        .where({
          status: 0,
          inout_type: 1,
        })
        .sum('money')) || 0;

    const unOutTotal =
      (await this.model('zengzhi_detail')
        .where({ status: 0, inout_type: 2 })
        .sum('money')) || 0;

    return this.success({
      incomeTotal: incomeTotal,
      outputTotal: outputTotal,
      lirunTotal: BigNumber(incomeTotal)
        .minus(BigNumber(outputTotal))
        .toFixed(2),
      unInTotal: unInTotal,
      unOutTotal: unOutTotal,
    });
  }

  async vatLineAction() {
    const dateFilter = this.post('t');

    const s = moment(dateFilter[0]);
    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const types = [
      {
        name: '收入',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
      {
        name: '支出',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
      {
        name: '利润',
        type: 'line',
        startData: moment(dateFilter[0]),
      },
    ];

    const data = {
      data: [],
    };
    const xData = [];
    const num = end.diff(start, 'months');

    for (let i = 0; i < num; i++) {
      xData.push(start.add(1, 'months').format('YYYY-MM'));
    }

    data.xData = xData;

    for (const item of types) {
      const addData = {
        name: item.name,
        type: item.type,
        showSymbol: false,
        data: [],
        tooltip: {
          // valueFormatter: function(value) {
          //   return value + ' °C';
          // },
        },
      };

      for (let i = 0; i < num; i++) {
        if (item.name === '收入') {
          const totalIncome =
            (await this.model('zengzhi_detail')
              .where({
                status: 1,
                inout_type: 1,
                update_time: [
                  'between',
                  s.format('YYYY-MM-DD HH:MM'),
                  item.startData
                    .add(1, 'months')
                    .endOf('month')
                    .format('YYYY-MM-DD HH:MM'),
                ],
              })
              .sum('money')) || 0;
          addData.data.push(totalIncome);
        } else if (item.name === '支出') {
          const totalOutput =
            (await this.model('zengzhi_detail')
              .where({
                status: 1,
                inout_type: 2,
                update_time: [
                  'between',
                  s.format('YYYY-MM-DD HH:MM'),
                  item.startData
                    .add(1, 'months')
                    .endOf('month')
                    .format('YYYY-MM-DD HH:MM'),
                ],
              })
              .sum('money')) || 0;
          addData.data.push(totalOutput);
        } else {
          const n = BigNumber(data.data[0].data[i])
            .minus(BigNumber(data.data[1].data[i]))
            .toFixed(2);
          addData.data.push(n);
        }
      }
      data.data.push(addData);
    }
    return this.success(data);
  }

  async vatShouzhiAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const income = await this.model('zengzhi_detail')
      .where({
        inout_type: 1,
        status: 1,
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const output = await this.model('zengzhi_detail')
      .where({
        status: 1,
        inout_type: 2,
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const arr = [
      {
        name: '收入',
        value: income || 0,
      },
      {
        name: '支出',
        value: output || 0,
      },
    ];

    return this.success(arr);
  }

  async vatShouzhiCateAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const types = [
      {
        name: '收入',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
      {
        name: '支出',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
    ];

    const data = {
      data: [],
    };
    const xData = [];

    const dictList = await this.model('dict_item')
      .where({ type: 'project_type' })
      .select();
    console.log(dictList, 777);

    for (const item of dictList) {
      xData.push(item.label);
    }

    data.xData = xData;

    for (const item of types) {
      const addData = {
        name: item.name,
        type: item.type,
        showSymbol: false,
        data: [],
        tooltip: {
          // valueFormatter: function(value) {
          //   return value + ' °C';
          // },
        },
      };

      for (const itemType of dictList) {
        if (item.name === '收入') {
          const totalIncome =
            (await this.model('zengzhi_detail')
              .alias('a')
              .join({
                contract_list: {
                  join: 'left',
                  as: 'c',
                  on: ['contract_id', 'id'],
                },
              })
              .where({
                'a.status': 1,
                'a.inout_type': 1,
                'c.contract_type': itemType.id,
              })
              .sum('money')) || 0;
          addData.data.push(totalIncome);
        } else if (item.name === '支出') {
          const totalOutput =
            (await this.model('zengzhi_detail')
              .alias('a')
              .join({
                contract_list: {
                  join: 'left',
                  as: 'c',
                  on: ['contract_id', 'id'],
                },
              })
              .where({
                'a.status': 1,
                'a.inout_type': 2,
                'c.contract_type': itemType.id,
              })
              .sum('money')) || 0;
          addData.data.push(totalOutput);
        }
      }
      data.data.push(addData);
    }
    return this.success(data);
  }

  // async vatYajinAction() {
  //   const dateFilter = this.post('t');

  //   const start = moment(dateFilter[0]).format('YYYY-MM-DD');
  //   const end = moment(dateFilter[1]).format('YYYY-MM-DD');

  //   const list = await this.model('income_list')
  //     .where({
  //       type: 'yajin',
  //       status: 1,
  //       update_time: ['between', [start, end]],
  //     })
  //     .select();
  //   const arr = [];
  //   for (const item of list) {
  //     const has = arr.find((res) => {
  //       if (res.name === item.yajin_type_str) {
  //         res.value = BigNumber(res.value)
  //           .plus(BigNumber(item.money))
  //           .toFixed(2);
  //       }
  //       return res.name === item.yajin_type_str;
  //     });
  //     if (!has) {
  //       arr.push({
  //         name: item.yajin_type_str,
  //         value: item.money || 0,
  //       });
  //     }
  //   }
  //   return this.success(arr);
  // }

  async vatCatgoryAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const dictList = await this.model('dict_item')
      .where({ type: 'project_type' })
      .select();

    const list = await this.model('zengzhi_detail')
      .where({
        'a.status': 1,
        'a.inout_type': 1,
        'a.update_time': ['between', [start, end]],
      })
      .alias('a')
      .join({
        contract_list: {
          join: 'left',
          as: 'c',
          on: ['contract_id', 'id'],
        },
      })
      .field('a.*, c.contract_type')
      .select();
    const arr = [];
    for (const item of list) {
      let typeName;

      dictList.forEach((element) => {
        if (element.id === item.contract_type) {
          typeName = element;
        }
      });

      if (!typeName) {
        continue;
      }

      const has = arr.find((res) => {
        if (res.name === typeName.label) {
          res.value = BigNumber(res.value)
            .plus(BigNumber(item.money))
            .toFixed(2);
        }
        return res.name === typeName.label;
      });
      if (!has) {
        arr.push({
          name: typeName.label,
          value: item.money || 0,
        });
      }
    }
    return this.success(arr);
  }

  async vatOutputAction() {
    const dateFilter = this.post('t');

    const s = moment(dateFilter[0]);
    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const dictList = await this.model('dict_item')
      .where({ type: 'project_type' })
      .select();

    const data = {
      data: [],
    };

    for (const item of dictList) {
      item.startData = moment(dateFilter[0]);
    }

    const xData = [];
    const num = end.diff(start, 'months');

    for (let i = 0; i < num; i++) {
      xData.push(start.add(1, 'months').format('YYYY-MM'));
    }

    data.xData = xData;

    for (const dictItem of dictList) {
      const addData = {
        name: dictItem.label,
        type: 'bar',
        stack: 'total',
        // label: {
        //   show: true,
        // },
        // emphasis: {
        //   focus: 'series',
        // },
        barWidth: 25,
        data: [],
        // tooltip: {
        //   valueFormatter: function(value) {
        //     return value + ' °C';
        //   },
        // },
      };
      for (let i = 0; i < num; i++) {
        const totalOutput =
          (await this.model('zengzhi_detail')
            .alias('a')
            .join({
              contract_list: {
                join: 'left',
                as: 'c',
                on: ['contract_id', 'id'],
              },
            })
            .where({
              'a.status': 1,
              'a.inout_type': 2,
              'c.contract_type': dictItem.id,
              update_time: [
                'between',
                s.format('YYYY-MM-DD HH:MM'),
                dictItem.startData
                  .add(1, 'months')
                  .endOf('month')
                  .format('YYYY-MM-DD HH:MM'),
              ],
            })
            .sum('money')) || 0;
        addData.data.push(totalOutput);
      }
      data.data.push(addData);
    }
    return this.success(data);
  }

  async vatContractAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const dictList = await this.model('dict_item')
      .where({ type: 'project_type' })
      .select();

    const data = [];

    for (const dictItem of dictList) {
      const count = await this.model('contract_list')
        .where({
          type: 3,
          contract_type: dictItem.id,
          date_start: [
            'between',
            start.format('YYYY-MM-DD HH:MM'),
            end.format('YYYY-MM-DD HH:MM'),
          ],
        })
        .count();
      data.push({
        name: dictItem.label,
        value: count || 0,
      });
    }
    return this.success(data);
  }
};
